import time
import signal
import socket
import select
import threading
import logging
from rich.logging import RichHandler

class TransServer:
    def __init__(self):
        self.run = False
        self.ip = None
        self.port = None
        self.__log_init()


    def __log_init(self):
        self.logger = logging.getLogger("T-Server")


    def config(self, ip, port):
        self.logger.debug('config.enter')
        self.ip = ip
        self.port = port
        self.logger.debug('config.done')


    def open(self):
        self.logger.debug('open.enter')
        self.logger.debug('open.done')


    def close(self):
        self.logger.debug('close.enter')
        self.logger.debug('close.done')


    def thread(self):
        self.logger.debug('thread.enter')

        address = (self.ip, self.port)
        self.ser = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.ser.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.ser.bind(address)
        self.ser.listen(1)
        self.logger.info("trans server start!")

        while self.run:
            readable, _, _ = select.select([self.ser], [], [], 1)
            if not readable:
                continue

            cli, addr = self.ser.accept()
            self.logger.info("accpet, client addr: %s", addr)

            try:
                message = cli.recv(1024).decode('utf-8')
            finally:
                cli.close()

        self.ser.close()
        self.logger.debug('thread.done')


    def start(self):
        self.logger.debug('start.enter')

        self.run = True
        self.handle = threading.Thread(target=self.thread)
        self.handle.start()

        self.logger.debug('start.done')
        return True


    def stop(self):
        self.logger.debug('stop.enter')

        self.run = False
        self.handle.join()

        self.logger.debug('stop.done')


exit = False

def handler(signum, frame):
    print('')
    global exit
    exit = True


def main():
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s %(name)-8s %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S',
        handlers=[RichHandler()])

    signal.signal(signal.SIGINT, handler)
    signal.signal(signal.SIGTERM, handler)

    server = TransServer()
    server.open()
    server.config('172.17.0.2', 8820)
    server.start()

    while not exit:
        time.sleep(0.2)

    server.stop()
    server.close()


if __name__ == "__main__":
    main()